package utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.json.JSONObject;
import android.util.Log;
import utils.MyException.HttpRequestException;

/**
 * 请求API，向服务器请求数据
 * 
 * @author king
 * 
 */
public class HttpRequestAndResponse {
	/**
	 * put方式请求接口
	 * 
	 * @param urlString
	 * @param params
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public JSONObject doPut(String urlString, Map<String, String> params) throws UnsupportedEncodingException {

		HttpURLConnection connection = null;
		JSONObject jsonObject = null;
		StringBuilder urlBuilder = new StringBuilder();

		if (null != params) {

			Iterator<Entry<String, String>> iterator = params.entrySet().iterator();

			while (iterator.hasNext()) {
				Entry<String, String> param = iterator.next();
				urlBuilder.append(URLEncoder.encode(param.getKey(), "UTF-8")).append('=')
						.append(URLEncoder.encode(param.getValue(), "UTF-8"));
				if (iterator.hasNext()) {
					urlBuilder.append('&');
				}
			}
		}

		try {
			URL url = new URL(urlString);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("PUT");
			connection.setDoOutput(true);// 设置允许写出
			connection.setDoInput(true);// 设置允许写入
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 请求头,必须设置
			connection.setRequestProperty("Accept", "application/json");// 请求头,必须设置
			connection.setRequestProperty("Content-Length", urlBuilder.length() + "");// 注意是字节长度,
			connection.setReadTimeout(8 * 1000);
			connection.setConnectTimeout(8 * 1000);

			OutputStream os = connection.getOutputStream();
			os.write(urlBuilder.toString().getBytes());
			os.close();

			Log.e("yiqijiao", "put+++connection.getResponseCode()=" + connection.getResponseCode());
			// 接受服务器返回数据
			if (connection.getResponseCode() == 200) {
				InputStream in = connection.getInputStream();// 获取读取流

				BufferedReader reader = new BufferedReader(new InputStreamReader(in));// 读取流缓冲区

				StringBuilder sb = new StringBuilder();

				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}

				jsonObject = new JSONObject(sb.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} // 获取到服务器返回的数据，如要使用这些数据，需要解析json数据，Android有相关API
		return jsonObject;

	}

	/**
	 * HttpURLConnection进行http请求，请求方式为get
	 * 
	 * @param urlString
	 *            服务器地址+接口路径
	 * @param params
	 *            传递的参数键值对
	 * @return 服务器返回的jsonObject对象
	 * @throws Exception
	 */
	public JSONObject doGet(String urlString, Map<String, String> params) throws Exception {

		HttpURLConnection connection = null;
		JSONObject jsonObject = null;
		StringBuilder urlBuilder = new StringBuilder();

		urlBuilder.append(urlString);

		if (null != params) {

			urlBuilder.append("?");

			Iterator<Entry<String, String>> iterator = params.entrySet().iterator();

			while (iterator.hasNext()) {
				Entry<String, String> param = iterator.next();
				urlBuilder.append(URLEncoder.encode(param.getKey(), "UTF-8")).append('=')
						.append(URLEncoder.encode(param.getValue(), "UTF-8"));
				if (iterator.hasNext()) {
					urlBuilder.append('&');
				}
			}
		}

		URL url = new URL(urlBuilder.toString());
		connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("GET");
		connection.setReadTimeout(20 * 1000);
		connection.setConnectTimeout(20 * 1000);
		Log.e("yiqijiao", "connection.getResponseCode()=" + connection.getResponseCode());
		if (connection.getResponseCode() == 200) {
			InputStream in = connection.getInputStream();// 获取读取流

			BufferedReader reader = new BufferedReader(new InputStreamReader(in));// 读取流缓冲区

			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}

			jsonObject = new JSONObject(sb.toString());
		}
		return jsonObject;
	}

	/**
	 * 加入了自定义请求头的get请求
	 * 
	 * @param urlString
	 *            服务器地址
	 * @param params
	 *            参数
	 * @param sessionHeader
	 *            请求头参数：用户的session_id
	 * @param roleHeader
	 *            用户的身份
	 * @return
	 * @throws Exception
	 */
	public JSONObject doGet(String urlString, Map<String, String> params, String sessionHeader, String roleHeader)
			throws Exception {

		HttpURLConnection connection = null;
		JSONObject jsonObject = null;
		StringBuilder urlBuilder = new StringBuilder();

		urlBuilder.append(urlString);

		if (null != params) {

			urlBuilder.append("?");

			Iterator<Entry<String, String>> iterator = params.entrySet().iterator();

			while (iterator.hasNext()) {
				Entry<String, String> param = iterator.next();
				urlBuilder.append(URLEncoder.encode(param.getKey(), "UTF-8")).append('=')
						.append(URLEncoder.encode(param.getValue(), "UTF-8"));
				if (iterator.hasNext()) {
					urlBuilder.append('&');
				}
			}
		}

		URL url = new URL(urlBuilder.toString());
		connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("GET");
		connection.setRequestProperty("YQJ-APP-USER-SESSION-ID", sessionHeader);
		connection.setRequestProperty("YQJ-APP-USER-ROLE", roleHeader);
		connection.setReadTimeout(20 * 1000);
		connection.setConnectTimeout(20 * 1000);
		Log.e("yiqijiao", "connection.getResponseCode()=" + connection.getResponseCode());
		if (connection.getResponseCode() == 200) {
			InputStream in = connection.getInputStream();// 获取读取流

			BufferedReader reader = new BufferedReader(new InputStreamReader(in));// 读取流缓冲区

			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}

			jsonObject = new JSONObject(sb.toString());
		}
		return jsonObject;
	}

	/**
	 * HttpURLConnection进行http请求，请求方式为post
	 * 
	 * @param urlString
	 *            服务器地址+接口路径
	 * @param params
	 *            传递的参数键值对
	 * @return 服务器返回的jsonObject对象
	 * @throws Exception
	 * 
	 */

	public JSONObject doPost(String urlString, Map<String, String> params) throws Exception {
		JSONObject jsonObject = null;
		InputStream in;

		StringBuilder urlBuilder = new StringBuilder();

		if (null != params) {

			Iterator<Entry<String, String>> iterator = params.entrySet().iterator();

			while (iterator.hasNext()) {
				Entry<String, String> param = iterator.next();
				urlBuilder.append(URLEncoder.encode(param.getKey(), "UTF-8")).append("=")
						.append(URLEncoder.encode(param.getValue(), "UTF-8"));
				if (iterator.hasNext()) {
					urlBuilder.append('&');
				}
			}
		}

		URL url = new URL(urlString);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(20000);
		// 这是请求方式为POST
		conn.setRequestMethod("POST");
		// 设置post请求必要的请求头
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 请求头,必须设置
		conn.setRequestProperty("Accept", "application/json");
		conn.setRequestProperty("Content-Length", urlBuilder.length() + "");// 注意是字节长度,

		conn.setDoOutput(true);// 设置允许写出
		conn.setDoInput(true);// 设置允许写入
//		conn.setUseCaches(false);//设置不允许使用缓存
		// 写出数据
		OutputStream os = conn.getOutputStream();
		os.write(urlBuilder.toString().getBytes());
		os.flush();
		os.close();

		Log.e("yiqijiao", "doPost=" + conn.getResponseCode());

		if (conn.getResponseCode() == 201) {
			in = conn.getInputStream();// 获取读取流
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));// 读取流缓冲区
			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}

			jsonObject = new JSONObject(sb.toString());

			reader.close();
			
		}else{
			Log.e("yiqijiao", "doPost=" + conn.getResponseCode());
			in=conn.getErrorStream();//读取错误流
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			Log.e("yiqijiao", sb.toString());
			
			jsonObject = new JSONObject(sb.toString());
			reader.close();
			
			throw new HttpRequestException();
		}
		return jsonObject;
	}

	public JSONObject doDelete(String urlString, Map<String, String> params) throws Exception {

		HttpURLConnection connection = null;
		JSONObject jsonObject = null;
		StringBuilder urlBuilder = new StringBuilder();

		urlBuilder.append(urlString);

		if (null != params) {

			urlBuilder.append("?");

			Iterator<Entry<String, String>> iterator = params.entrySet().iterator();

			while (iterator.hasNext()) {
				Entry<String, String> param = iterator.next();
				urlBuilder.append(URLEncoder.encode(param.getKey(), "UTF-8")).append('=')
						.append(URLEncoder.encode(param.getValue(), "UTF-8"));
				if (iterator.hasNext()) {
					urlBuilder.append('&');
				}
			}
		}

		URL url = new URL(urlBuilder.toString());
		connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("DELETE");
		connection.setReadTimeout(20 * 1000);
		connection.setConnectTimeout(20 * 1000);
		Log.e("yiqijiao", "connection.getResponseCode()=" + connection.getResponseCode());
		if (connection.getResponseCode() == 200) {
			InputStream in = connection.getInputStream();// 获取读取流

			BufferedReader reader = new BufferedReader(new InputStreamReader(in));// 读取流缓冲区

			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}

			jsonObject = new JSONObject(sb.toString());
		}
		return jsonObject;
	}
}
